#include <FS.h> //ESP设备内置FileSystem,可操作FLASH
#include <ArduinoJson.h>
#include <ESP8266WiFi.h> //可创建WIFI热点
#include <WiFi.h>
#include "fetchinfo.h"
#include "state.h"
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Wifi
const char *ssid = "Super 80";
const char *password = "";
const char *SSIDFile = "/ssid.json";
void WiFiEvent(WiFiEvent_t event);
void WifiConfig(DynamicJsonDocument &doc) {
    fs::File file = SPIFFS.open(SSIDFile, "w");
    if(file) {
      serializeJson(doc,file);
      file.close();
    }
}
void StartWifiAP() {
    WiFi.softAP(ssid, password);
}
void LoadWifiConfig() {
  if(SPIFFS.begin()) {
    fs::File file = SPIFFS.open(SSIDFile, "r");
    if (file) {
      DynamicJsonDocument doc(1024);
      DeserializationError err =  deserializeJson(doc,file);
      if(!err) {
        String ssid = doc["ssid"];
        String passwd = doc["password"];
        String wapi = doc["weather-api"];
        String city = doc["city"];
        Serial.println(ssid);
        Serial.println(passwd);
        Serial.println(wapi);
        InfoConfig(city,wapi);
        //WiFi.onEvent(WiFiEvent);
        Serial.println("Try to connect WiFi");
        TryConnectWifi(ssid,passwd);
      } else {
        printf("Failed to read file");
        return;
      }
      State = STATE_WIFI_DISCONNECTED;
      if(WiFi.status() != WL_CONNECTED) {
        //HandleWifiConfig();
        Serial.println("WiFi not connected");
      } else {
        Serial.println("WiFi connected");
      }
    } else {
      Serial.println("File not ready");
    }
  } else {
    Serial.println("SPIFFS not ready");
  }
}

int maxRetries = 3;
int retryCount = 0;
// void WiFiEvent(WiFiEvent_t event) {
//   Serial.print("WiFi event");
//   Serial.println(event);
//   switch (event) {
//     case WIFI_EVENT_STAMODE_CONNECTED:
//       State = STATE_WIFI_CONNECTED;
//       retryCount = 0;
//       break;
//     case WIFI_EVENT_STAMODE_DISCONNECTED:
//       State = STATE_WIFI_DISCONNECTED;
//       Serial.println("WiFi connection lost");
//       TryReconnectWifi();
//       break;
//     default:
//       break;
//   }
// }
void TryConnectWifi(String ssid, String passwd) {
  WiFi.begin(ssid, passwd);
  unsigned long startAttempt = millis();
  while(WiFi.status() != WL_CONNECTED) { // wait for the Wi-Fi to connect
    delay(500);
    if(millis() - startAttempt > 5000) {
      break;
    }
  }
}
void TryReconnectWifi() {
  if (retryCount < maxRetries) {
    Serial.println("Attempting to reconnect...");
    unsigned long startAttempt = millis();
    WiFi.reconnect();
    while(WiFi.status() != WL_CONNECTED) { // wait for the Wi-Fi to connect
      delay(500);
      if(millis() - startAttempt > 5000) {
        break;
      }
    }
    retryCount++;
  } else {
    Serial.println("Max retries reached. Restarting ESP32...");
    ESP.restart();
  }
}